﻿using System;
using MetaMapics.Pbf;
using MetaMapics.Pbf.Indexed;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTest_MetaMapics.Pbf
{
  [TestClass]
  public class UnitTest_IndexedPbf
  {
    private class TestClass : IPbfStreamable, IEquatable<TestClass>
    {
      public string Name { get; set; }
      public int Number { get; set; }

      public void WriteToPbf(PbfWriter writer)
      {
        writer.Write(1, Name);
        writer.Write(2, Number);
      }

      public void ReadFromPbf(PbfReader reader)
      {
        foreach (int fieldNum in reader.Fields())
          switch (fieldNum)
          {
            case 1:
              Name = reader.ReadString();
              break;
            case 2:
              Number = reader.ReadInt();
              break;
            default:
              reader.IgnoreField();
              break;
          }
      }

      public bool Equals(TestClass other)
      {
        return Number == other.Number && (Name == null && other.Name == null || Name == other.Name);
      }
    }

    [TestMethod]
    public void TestNumericIndexedPbf()
    {
      TestClass a = new TestClass { Name = "Tom", Number = 321 };
      TestClass b = new TestClass { Name = "Dick", Number = 321 };
      TestClass c = new TestClass { Name = "Harry", Number = 321 };
      using (var indexedWriter = new NumericIndexedPbfWriter<TestClass>("ttt.pbf"))
      {
        indexedWriter.Add(123,a);
        indexedWriter.Add(789, b);
        indexedWriter.Add(456, c);
        indexedWriter.WriteIndex();
      }
      using (var reader = new NumericIndexedPbfReader<TestClass>("ttt.pbf"))
      {
        TestClass a1, b1, c1, d1;

        Assert.IsTrue(reader.Get(789, out b1));
        Assert.IsTrue(reader.Get(123, out a1));
        Assert.IsTrue(reader.Get(456, out c1));
        Assert.IsFalse(reader.Get(666, out d1));

        Assert.IsTrue(a.Equals(a1));
        Assert.IsTrue(b.Equals(b1));
        Assert.IsTrue(c.Equals(c1));
      }
    }
  }
}
